package com.ligongmusic.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.ligongmusic.R;
import com.ligongmusic.domain.Person;
import com.ligongmusic.util.DialogUtils;
import com.ligongmusic.util.DialogUtils.SelectCallBack;
import com.ligongmusic.util.ActivityManager;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.TopManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class UserInformation extends Activity {
    private long timeMillis = -1;
    //	private TextView admission_time;// 入学时间
    private TextView tv_college;// 院系
    private Person person;
    private Uri uritempFile;
    private TextView tv_sex;
    private ImageView iv_icon;
    private EditText etNickName;
    //	private EditText name;
//	private EditText et_phone;
    private EditText et_class;
    private int isWhut = -1;
    private EditText et_student_id;
    private EditText et_introduction;
    private Bitmap bitmap;
    private Handler mHandler = new Handler();
    private String[] part, partIds;
    private int selectPart = -1;
    private boolean click = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload_info);
        // 获取用户信息
        person = (Person) getIntent().getSerializableExtra("info");
        if (person == null)
            person = new Person();
        initView();
        getPartment();
    }

    private void initView() {
        // 改变标题
        TopManager.getTopManager(UserInformation.this).showTop(true, "个人信息", new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 头像
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        try {
            if (!StringUtils.isEmpty(person.getPhoto()))
                new Thread() {
                    @Override
                    public void run() {
                        bitmap = ImageLoader.getInstance().loadImageSync(GlobalParams.IMAGE_URL + person.getPhoto());
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (bitmap != null)
                                    iv_icon.setImageBitmap(bitmap);
                            }
                        });
                    }
                }.start();
        } catch (Exception e) {
            // 获取图片失败
        }
        // 昵称
        etNickName = (EditText) findViewById(R.id.et_nick_name);
        etNickName.setText(StringUtils.isEmpty(person.getNickname()) ? "" : person.getNickname());
        // 姓名
//		name = (EditText) findViewById(R.id.et_name);
//		name.setText(StringUtils.isEmpty(person.getPersonname()) ? "" : person.getPersonname());
        // 性别
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_sex.setText(StringUtils.isEmpty(person.getSex()) ? "" : person.getSex());
        ((RelativeLayout) findViewById(R.id.rl_select_sex)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.selectDialog(UserInformation.this, new String[]{"男", "女"}, new SelectCallBack() {
                    @Override
                    public void select(String item) {
                        tv_sex.setText(item);
                    }
                });
            }
        });
        // 手机号
//		et_phone = (EditText) findViewById(R.id.et_phone);
//		et_phone.setText(StringUtils.isEmpty(person.getPersonphone()) ? "" : person.getPersonphone());
        // 班级
//		et_class = (EditText) findViewById(R.id.et_class);
//		et_class.setText(StringUtils.isEmpty(person.getClasses()) ? "" : person.getClasses());
//		// 学号
        et_student_id = (EditText) findViewById(R.id.et_student_id);
        et_student_id.setText(StringUtils.isEmpty(person.getStudentid()) ? "" : person.getStudentid());
        // 个人简介
        et_introduction = (EditText) findViewById(R.id.et_introduction);
        et_introduction.setText(StringUtils.isEmpty(person.getIntroduction()) ? "" : person.getIntroduction());
        if (person.getIswhutstudent() == 1) {
            ((ImageView) findViewById(R.id.arrow_whut)).setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv_whut)).setText("本校生");
            ((TextView) findViewById(R.id.tv_whut)).setVisibility(View.VISIBLE);
            isWhut = 1;
            ((LinearLayout) findViewById(R.id.ll_whut)).setVisibility(View.VISIBLE);
        } else if (person.getIswhutstudent() == 0) {
            ((ImageView) findViewById(R.id.arrow_whut)).setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv_whut)).setText("非本校生");
            ((TextView) findViewById(R.id.tv_whut)).setVisibility(View.VISIBLE);
            ((LinearLayout) findViewById(R.id.ll_whut)).setVisibility(View.GONE);
            isWhut = 0;
        }
        // 是否本校生
        ((RelativeLayout) findViewById(R.id.rl_is_whut)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.selectDialog(UserInformation.this, new String[]{"本校生", "非本校生"}, new SelectCallBack() {
                    @Override
                    public void select(String item) {
                        if (!StringUtils.isEmpty(item)) {
                            ((ImageView) findViewById(R.id.arrow_whut)).setVisibility(View.GONE);
                            ((TextView) findViewById(R.id.tv_whut)).setText(item);
                            ((TextView) findViewById(R.id.tv_whut)).setVisibility(View.VISIBLE);
                            if ("本校生".equals(item)) {
                                isWhut = 1;
                                ((LinearLayout) findViewById(R.id.ll_whut)).setVisibility(View.VISIBLE);
                            } else {
                                ((LinearLayout) findViewById(R.id.ll_whut)).setVisibility(View.GONE);
                                isWhut = 0;
                            }
                        }
                    }
                });
            }
        });
//		admission_time = (TextView) findViewById(R.id.tv_admission_time);
//		if(person.getAdmissiontime() != null && person.getAdmissiontime() > 0){
//			// 获取毫秒值，上传使用
//			timeMillis = person.getAdmissiontime();
//			admission_time.setVisibility(View.VISIBLE);
//			((ImageView)findViewById(R.id.admission_arrow)).setVisibility(View.GONE);
//			admission_time.setText(StringUtils.getYear(person.getAdmissiontime()));
//		}
        tv_college = (TextView) findViewById(R.id.tv_college);
//		if(!StringUtils.isEmpty(person.getDepartmentid() + "")){
//			tv_college.setText(person.getDepartmentid() + "");
//			tv_college.setVisibility(View.VISIBLE);
//			((ImageView)findViewById(R.id.college_arrow)).setVisibility(View.GONE);
//		}
        // 入学时间选择
//		((RelativeLayout)findViewById(R.id.rl_time)).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				final Calendar c = Calendar.getInstance();
//				int mYear = c.get(Calendar.YEAR);
//				int mMonth = c.get(Calendar.MONTH);
//				int mDay = c.get(Calendar.DAY_OF_MONTH);
//				new DatePickerDialog(UserInformation.this, new OnDateSetListener() {
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//						// 获取毫秒值，上传使用
//						timeMillis = c.getTimeInMillis();
//						admission_time.setVisibility(View.VISIBLE);
//						((ImageView)findViewById(R.id.admission_arrow)).setVisibility(View.GONE);
//						admission_time.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
//					}
//				},mYear, mMonth, mDay).show();
//			}
//		});
        // 院系选择
        ((RelativeLayout) findViewById(R.id.rl_college)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (part == null)
                    return;
                DialogUtils.selectDialog(UserInformation.this, part, new SelectCallBack() {
                    @Override
                    public void select(String item) {
                        for (int i = 0; i < part.length; i++) {
                            if (part[i].equals(item)) {
                                selectPart = Integer.parseInt(partIds[i]);
                            }
                        }
                        tv_college.setText(item);
                        LoggerUtils.getLog(UserInformation.class).error(selectPart + "");
                        tv_college.setVisibility(View.VISIBLE);
                        ((ImageView) findViewById(R.id.college_arrow)).setVisibility(View.GONE);
                    }
                });
            }
        });
        // 头像选择
        ((RelativeLayout) findViewById(R.id.rl_upload)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.selectDialog(UserInformation.this, new String[]{"相册", "拍照"}, new SelectCallBack() {
                    @Override
                    public void select(String item) {
                        if (item.contains("相册")) {
                            Intent intent = new Intent();
                            /* 开启Pictures画面Type设定为image */
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            //						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
							/* 取得相片后返回本画面 */
                            startActivityForResult(intent, 0x1);
                        } else {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 0x1);
                        }
                    }
                });
            }
        });
        // 上传
        ((Button) findViewById(R.id.bt_upload)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				if(bitmap == null){
//					Toast.makeText(getApplicationContext(), "请选择要上传的头像", Toast.LENGTH_SHORT).show();
//					return;
//				}
                if (!click)
                    return;
                String nickName = etNickName.getText().toString().trim();
                if (StringUtils.isEmpty(nickName)) {
                    Toast.makeText(getApplicationContext(), "请输入昵称", Toast.LENGTH_SHORT).show();
                    return;
                }
//				String userName = name.getText().toString().trim();
//				if(StringUtils.isEmpty(userName)){
//					Toast.makeText(getApplicationContext(), "请输入姓名", Toast.LENGTH_SHORT).show();
//					return;
//				}
                String sex = tv_sex.getText().toString().trim();
                if (StringUtils.isEmpty(sex)) {
                    Toast.makeText(getApplicationContext(), "请选择性别", Toast.LENGTH_SHORT).show();
                    return;
                }
//				String phone = et_phone.getText().toString().trim();
//				if(StringUtils.isEmpty(phone)){
//					Toast.makeText(getApplicationContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
//					return;
//				}
//				if(!StringUtils.isMobile(phone)){
//					Toast.makeText(getApplicationContext(), "手机号不合法", Toast.LENGTH_SHORT).show();
//					return;
//				}
//				if(timeMillis == -1){
//					Toast.makeText(getApplicationContext(), "请选择入学时间", Toast.LENGTH_SHORT).show();
//					return;
//				}
                if (isWhut == -1) {
                    Toast.makeText(getApplicationContext(), "请选择是否本校生", Toast.LENGTH_SHORT).show();
                    return;
                }
                String studentId = et_student_id.getText().toString().trim();
                String college = tv_college.getText().toString().trim();
                if (isWhut == 1) {
                    if (StringUtils.isEmpty(college) || selectPart == -1) {
                        Toast.makeText(getApplicationContext(), "请选择院系", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (StringUtils.isEmpty(studentId) || selectPart == -1) {
                        Toast.makeText(getApplicationContext(), "请输入学号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
//				String etClass = et_class.getText().toString().trim();
//				if(StringUtils.isEmpty(etClass)){
//					Toast.makeText(getApplicationContext(), "请输入班级", Toast.LENGTH_SHORT).show();
//					return;
//				}
                click = false;
                String introduction = et_introduction.getText().toString().trim();
                try {
                    Map<String, Object> maps = new HashMap<String, Object>();
                    maps.put("photo", bitmap == null ? "" : bitmap);
                    maps.put("nickname", nickName);
                    maps.put("iswhutstudent", isWhut + "");
                    maps.put("token", GlobalParams.token);
                    maps.put("loginname", GlobalParams.userName);
//					maps.put("personname", userName);
                    maps.put("sex", sex);
//					maps.put("personphone", phone);
//					maps.put("admissiontime", timeMillis + "");
                    maps.put("departmentid", isWhut == 1 ? selectPart + "" : "");
//					maps.put("classes", etClass);
                    maps.put("studentno", isWhut == 1 ? studentId : "");
                    maps.put("introduction", introduction);
                    NetWorkUtils.uploadInfo("jpg", GlobalParams.UPLOAD_INFORMATION, maps, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            click = true;
                            Toast.makeText(getApplicationContext(), JsonUtils.getString(responseInfo.result, "message"), Toast.LENGTH_SHORT).show();
                            String code = JsonUtils.getString(responseInfo.result, "code");
                            if ("200".equals(code)) {
                                setResult(0x1);
                                finish();
                            }
//							LoggerUtils.getLog(MainActivity.class).error(responseInfo.result);
//							LoggerUtils.getLog(MainActivity.class).error("------------------");
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            click = true;
                            Toast.makeText(getApplicationContext(), "修改失败，请重试", Toast.LENGTH_SHORT).show();
                            LoggerUtils.getLog(UserInformation.class).error(msg);
                            LoggerUtils.getLog(UserInformation.class).error("------------------");
                        }
                    });
                } catch (IOException e) {
                    click = true;
//                    e.printStackTrace();
                }
            }
        });
    }


    private void getPartment() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        NetWorkUtils.getRequest(pairs, GlobalParams.DEPARTMENT, new NetWorkUtils.NetWorkCallBack() {
            @Override
            public void success(String result) {
                LoggerUtils.getLog(UserInformation.class).error(result);
                try {
                    JSONArray arr = new JSONArray(result);
                    part = new String[arr.length()];
                    partIds = new String[arr.length()];
                    for (int i = 0; i < arr.length(); i++) {
                        part[i] = arr.optJSONObject(i).optString("name");
                        partIds[i] = arr.optJSONObject(i).optString("id");
                        if (person.getDepartmentid() == null ? false : person.getDepartmentid() == Integer.parseInt(partIds[i])) {
                            selectPart = Integer.parseInt(partIds[i]);
                            tv_college.setText(part[i]);
                            tv_college.setVisibility(View.VISIBLE);
                            ((ImageView) findViewById(R.id.college_arrow)).setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error() {
            }

            @Override
            public void error(String message) {
                LoggerUtils.getLog(UserInformation.class).error(message);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x1) {
                Uri uri = getUri(data);
                crop(uri);
            } else if (requestCode == 0x11) {
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
                    iv_icon.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁  
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高  
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）  
         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题  
         */
        //intent.putExtra("return-data", true);        

        //uritempFile为Uri类变量，实例化uritempFile  
//        UUID uid = UUID.randomUUID();
//        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + uid.toString() + ".jpg");
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "xx.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, 0x11);
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri getUri2(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(Images.ImageColumns._ID);
                    // set _id value    
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing    
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }


    public Uri getUri(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换

        if (imageUri!=null) {
            String path = imageUri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
}
